package com.newland.starpos.partner.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newland.starpos.base.exception.CustomException;
import com.newland.starpos.common.CodeParam;
import com.newland.starpos.common.CodeSms;
import com.newland.starpos.common.Sms;
import com.newland.starpos.http.ResponseEnum;
import com.newland.starpos.http.ResponseModel;
import com.newland.starpos.utils.HttpUtil;
import com.newland.starpos.utils.StringUtils;

@Service
public class AuthCodeService {

	private static final Logger logger = LoggerFactory.getLogger(AuthCodeService.class);

	private static final String smsurl = "http://api.starpos.com.cn:8080/cloudpos/sms/singleSendSms";

	private static final String prodName = "合伙人app后台服务";

	public ResponseModel sendAuthCode(String phoneNumber) throws CustomException {

		String code = StringUtils.getAuthCode();
		Sms sms = buildCodeSms("", phoneNumber, code);
		String response = "";
		try {
			String content = JSON.toJSONString(sms);
			response = HttpUtil.submitRequest(smsurl, content, "application/json", "UTF8");
		} catch (Exception e) {
			logger.info("短信发送请求异常，异常信息：{}", e.getMessage());
			throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信发送请求异常");
		}
		if (StringUtils.isBlank(response)) {
			logger.info("短信服务返回异常，响应内容为空.");
			throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信服务返回异常");
		}

		// 解析返回结果
		JSONObject resp = JSON.parseObject(response);// 解析返回结果
		String respCode = (String) resp.get("code");// 获取响应码
		logger.info("短信服务返回的响应码：{}", respCode);

		// 返回结果处理
		switch (respCode) {
		case "success":
			JSONObject data = (JSONObject) resp.get("data");
			String requestId = data.getString("RequestId");
			logger.info("短信服务返回的RequestId：{}", requestId);
			break;
		case "failure":
			throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信发送结果为失败");
		default:
			throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信发送响应码不正确");
		}
		return new ResponseModel(ResponseEnum.OK);
	}

	public Sms buildCodeSms(String templateCode, String mobile, String code) {
		CodeSms sms = new CodeSms();
		sms.setRecnum(mobile);
		sms.setTemplatecode(templateCode);

		CodeParam param = new CodeParam();
		param.setCode(code);
		param.setProduct(prodName);
		sms.setParamstring(param);
		return sms;
	}
}
